<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  props:['country'],
  watch:{
    country: {
      handler(newName, oldName) {
        this.roomData = newName
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: true,
      deep: true // 开启深度监听，默认是false
    }
  },
  data() {
    return {
      map: null,
      cluster:null,
      roomData: [],
      district: {},
      // 设置不同组群不同缩放级别
      clusterIndexSet: {
        county:{
          minZoom: 1,
          maxZoom: 3,
        },
        province:{
          minZoom: 3,
          maxZoom: 5,
        },
        city: {
          minZoom: 5,
          maxZoom: 7,
        },
        district: {
          minZoom: 7,
          maxZoom: 16,
        },
      }

    }
  },
  created() {

  },
  mounted() {
    if(this.roomData.length == 0){
      this.roomData = JSON.parse(localStorage.getItem("country"))
    }
    this.getGis();
  },
  beforeDestroy() {
    this.map && this.map.destroy()
  },
  methods: {
    initPage(DistrictCluster, $, utils) {},
    getStyle(context) {
      var clusterData = context.clusterData; // 聚合中包含数据
      var index = context.index; // 聚合的条件
      var count = context.count; // 聚合中点的总数
      var marker = context.marker; // 聚合绘制点 Marker 对象
      var color = '8,60,156'
      // var color = [
      //   '8,60,156',
      //   '66,130,198',
      //   '107,174,214',
      //   '78,200,211',
      // ];
      var indexs = ['county','province','city', 'district'];
      var i = indexs.indexOf(index['mainKey']);
      var text = clusterData[0][index['mainKey']];
      var size = Math.round(30 + Math.pow(count / this.roomData.length, 1 / 5) * 70);
      if (i <= 4) {
        var extra = '<div style="margin-top:'+size /4+'px"><span class="showName">' + text + '</span><br/><span class="showCount">' + context.count + '</span></div>';

        text = extra;
      } else {
        size = 12 * text.length + 20;
      }
      var style = {
        bgColor: 'linear-gradient(139deg, #3BBFFF 0%, #17A1E3 100%)',//'rgba(' + color + ',.8)',
        opacity:'0.9',
        borderColor: 'rgba(' + color + ',1)',
        text: text,
        size: size,
        index: i,
        color: '#ffffff',
        textAlign: 'center',
        boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
      }
      return style;
    },
    getPosition(context) {
      var key = context.index.mainKey;
      var dataItem = context.clusterData && context.clusterData[0];
      var districtName = dataItem[key];
      if (!this.district[districtName]) {
        return null;
      }
      var center = this.district[districtName].center.split(',');
      var centerLnglat = new AMap.LngLat(center[0], center[1]);
      return centerLnglat;
    },
    _renderClusterMarker(context) {
      let that = this
      var clusterData = context.clusterData; // 聚合中包含数据
      var index = context.index; // 聚合的条件
      var count = context.count; // 聚合中点的总数
      var marker = context.marker; // 聚合点标记对象
      var styleObj = that.getStyle(context);
      // 自定义点标记样式
      var div = document.createElement('div');
      div.className = 'amap-cluster';
      div.style.background = styleObj.bgColor;
      div.style.opacity=styleObj.opacity;
      div.style.width = styleObj.size + 'px';
      if (styleObj.index <= 3) {
        div.style.height = styleObj.size + 'px';
        div.style.paddingTop = styleObj.size /4+ 'px';
        // div.style.lineHeight = styleObj.size /2+ 'px';
        // 自定义点击事件
        if(styleObj.index <= 2){
          context.marker.on('click', function(e) {
            var curZoom = that.map.getZoom();
            if (curZoom < 20) {
              curZoom += 1;
            }
            that.map.setZoomAndCenter(curZoom, e.lnglat);
          });
        }

      }
      // div.style.border = 'solid 1px ' + styleObj.borderColor;
      div.style.borderRadius = styleObj.size + 'px';
      div.innerHTML = styleObj.text;
      div.style.color = styleObj.color;
      div.style.textAlign = styleObj.textAlign;
      div.style.boxShadow = styleObj.boxShadow;
      div.style.fontSize = 16 + 'px'
      div.style.padding = `5px 0`;
      context.marker.setContent(div)
      // 自定义聚合点标记显示位置
      var position = that.getPosition(context);
      if (position) {
        context.marker.setPosition(position);
      }
      context.marker.setAnchor('center');

    },
    async getGis() {
      var that = this;
      AMapLoader.load({
        //注册开发者/创建应用，选择web端JS API（必须）
        key: '565fec4595b43debb5cc0bde7f20b9fb', //设置您的key
        version: "2.0",
        plugins: ['AMap.IndexCluster'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        },
        Loca: {
          version: '2.0'
        }
      }).then(() => {

        that.map = new AMap.Map('container', {
          iewMode: '3D', //使用3D视图
          zoom: 2, //级别
          resizeEnable: true,
          center: [119,32], //中心点坐标
          mapStyle: "amap://styles/macaron",
        });


        AMap.plugin([
          'AMap.ToolBar',
        ], function(){
          // 在图面添加工具条控件, 工具条控件只有缩放功能
          that.map.addControl(new AMap.ToolBar());
        });
        // var toolbar = new AMap.ToolBar();
        that.cluster = new AMap.IndexCluster(that.map, that.roomData, {
          renderClusterMarker: that._renderClusterMarker,
          clusterIndexSet: that.clusterIndexSet,
        });
        that.roomData.forEach(x=>{
          if(x.lgt!=null&&x.lat!=null){
            let marker = new AMap.Marker({
              position: new AMap.LngLat(x.lgt, x.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title: x.district
            });
            // 将创建的点标记添加到已有的地图实例：
            that.map.add(marker);
          }
        });
      }).catch((e) => {
        console.error(e);
      });
    },

  },


}
</script>

<style>
#container {
  height: 100%;
  width: 100%;
}

::v-deep.amap-cluster {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}

::v-deep.showName {
  font-size: 16px;
}

::v-deep.showCount,
::v-deep.showName {
  line-height: 20px;
  display: block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
